#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import glob
import codecs
import argparse

def get_time_stamp(line, idx=0):
    ts = line.split('.')[idx]
    ret = '%s\t%s'%(ts.split(':')[-1], line)
    return ts, ret

class scanner(object):
    def __init__(self):
        self.tlist = []

    def load_file(self, filename, fstr='', prefix='2017-'):
        with open(filename) as f:
            for l in f:
                if l.startswith(prefix):
                    if fstr:    # 如果需要过滤关键字
                        if not fstr in l: continue  # 未找到关键字继续向下
                    ts, ret = get_time_stamp(l)
                    if not ts in self.tlist:
                        self.tlist.append(ts)
                        print('%s\t%s'%(filename, ret.strip()))

    def load_files(self, files, fstr='', prefix='2017-'):
        for f in files:
            self.load_file(f, fstr, prefix)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="用于抽取日志中的时间秒数，可使用过滤选项")
    parser.add_argument("-f", "--filter", metavar='FILTER', type=str, help='设置过滤字符串，常用sw_status')
    parser.add_argument("files", nargs='+', type=str, help='输入多个日志文件，或输入通配符')
    args = parser.parse_args()

    sc = scanner()
    for key in args.files:
        files = glob.glob(key)
        sc.load_files(files, args.filter)
